package com.cxf.cxfribbononly.controller;

import com.cxf.cxfribbononly.repository.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.concurrent.ExecutionException;

@RequestMapping
@RestController

public class RibbonController {


    @Autowired
    private RestTemplate restTemplate;

    //注入负载均衡客户端
    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @GetMapping("/echo/{id}")
    public String getStoreInfo(@PathVariable("id") String id){
        String forObject = restTemplate.getForObject("http://cxf-store-demo/echo/"+id, String.class);
        System.out.println("收到响应信息：...."+forObject);
        return forObject;
    }

    @GetMapping("/user/{id}")
    public Order getOrderInfo(@PathVariable("id") String id){
        Order forObject = restTemplate.getForObject("http://cxf-order-demo/order/"+id, Order.class);
        System.out.println("收到响应信息：...."+forObject);
        return forObject;
    }

    @GetMapping("/echoUrl")
    public String echoUrl(){
        //这里是根据配置文件的那个providers属性取的
        ServiceInstance serviceInstance = loadBalancerClient.choose("cxfStoreDemo");
        //负载均衡算法默认是轮询，轮询取得服务
        URI uri = URI.create(String.format("http://%s:%s", serviceInstance.getHost(), serviceInstance.getPort()));
        return uri.toString();
    }


    @GetMapping("/consumer")
    public String helloConsumer() throws ExecutionException, InterruptedException {
        //这里是根据配置文件的那个providers属性取的
        ServiceInstance serviceInstance = loadBalancerClient.choose("cxfStoreDemo");
        //负载均衡算法默认是轮询，轮询取得服务
        URI uri = URI.create(String.format("http://%s:%s", serviceInstance.getHost(), serviceInstance.getPort()));
        return uri.toString();
    }
}
